<?php

	class Backend_UserController extends Zend_Controller_Action {
	
		public function init() {
			
			$am = new Model_Authentication();
			
			$this->view->action_name = $this->getRequest()->getActionName();
			$this->view->controller_name = $this->getRequest()->getControllername();
		
			// Logged
			if($am->isLoggued()){
				$user = $am->getlogguedInformations();
				
				$this->view->is_logged = true;
				$this->view->user = $user;
				
			// Not logged
			} else {
				if(	$this->view->action_name != 'signin' and
					$this->view->action_name != 'prc-signin') {
					
					$redirector = $this->_helper->getHelper('Redirector');
					$redirector->gotoRoute(array('controller' => 'index', 'action' => 'index'));
				}
				$this->view->is_logged = false;
			}
			
			$this->view->headLink()
					->appendStylesheet($this->_request->getBaseUrl().'/styles/commun.css')
					->appendStylesheet($this->_request->getBaseUrl().'/styles/template.css')
					->appendStylesheet($this->_request->getBaseUrl().'/styles/backend/user.css');
			
			// Ajax's call
		    $this->_helper->AjaxContext()
		         ->addActionContext('prc-signin', 'json')
		         ->initContext();
		    
		    $this->view->baseUrl = $this->_request->getBaseUrl();
			
			// change layout
            $layout = Zend_Layout::getMvcInstance();
			$layout->setLayout('layout_admin');
		}
		
		public function signinAction() {
			
			$this->view->headTitle('Hybrid Legacy - Administration - Connexion');
			
			$this->view->headLink()
					->appendStylesheet($this->_request->getBaseUrl().'/styles/backend/form.css');
					
			$this->view->headLink()
					->appendStylesheet($this->_request->getBaseUrl().'/styles/backend/signin.css');
					
			$this->view->jQuery()
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.form.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.rules_custom.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.messages_fr.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/backend/signin.js'));
			
		}
		
		public function prcSigninAction() {
			
			$uM = new Model_Authentication();
			
			// checking
			$errors = array();
			
			$email = $this->_request->getParam('email');
			$password = $this->_request->getParam('password');
			
			if(is_null($email) or empty($email)) {
				$errors[] = 'Veuillez indiquer votre adresse email';
			}
			
			if(is_null($password) or empty($password)) {
				$errors[] = 'Veuillez entrer votre mot de passe';
			}
			
			// errors
			if(!empty($errors)) {
				$message = 'Connexion impossible :<br />';
				foreach($errors as $e) {
					$message .= $e.'<br />';
				}
				$result = array('result' => false,
								'message' => $message
								);
			}
			
			// no errors
			$logged = $uM->authenticate($email, $password);
			
			// logged
			if($logged) {
				$result = array('result' => true,
								'message' => 'Connecté'
								);
			
			// not logged
			} else {
				$result = array('result' => false,
								'message' => 'Veuillez vérifier votre login et/ou votre mot de passe'
								);
				
				// add l
			}
			
			exit(Zend_Json::encode($result));
			
		}
		
		public function signoutAction() {
			
			$this->view->headTitle('Hybrid Legacy - Administration - Déconnexion');
			
			$aM = new Model_Authentication();
			$aM->logout();
					
			$redirector = $this->_helper->getHelper('Redirector');
			$redirector->gotoRoute(array('controller' => 'index', 'action' => 'index'));
			
		}
		
		
		public function setAction() {
			
			$this->view->headTitle('Hybrid Legacy - Administration - Gérer ma fiche');
					
			$this->view->headLink()
					->appendStylesheet($this->_request->getBaseUrl().'/styles/backend/form.css');
					
			$this->view->jQuery()
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.form.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.rules_custom.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.messages_fr.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/backend/user-set.js'));
			
			// limit access to admin and selected user
			$id = $this->_request->getParam('id');
			
			// if no id, use user's id
			if(is_null($id)) {
				$id = $this->view->user['id'];
			
			// if id exist
			// check if connected user is the selected user
			// else check if admin
			// if not admin, limit access
			} else {
				
				if($id != $this->view->user['id']) {
					
					// if admin
					$admin = false;
					foreach($this->view->user['groups'] as $g) {
						if(strtolower($g) == 'admin') {
							$admin = true;
						}
					}
					
					if(!$admin) {
						$this->view->error = 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche';
						exit(Zend_Json::encode(array('result' => false, 'message' => 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche')));
					}
				}
			}
			
			// get user's informations
			$uM = new Model_User();
			$filter = array('id' => $id);
			$user = $uM->get($filter);
			
			// change birth format
			$date_temp = explode(' ', $user[0]['birth']);
			$date_tab = explode('-', $date_temp[0]);
			$date = $date_tab[2].'/'.$date_tab[1].'/'.$date_tab[0];
			$user[0]['birth'] = $date;
			
			$this->view->datas = $user[0];
			
		}
		
		public function prcSetAction() {
		
			
			// limit access to admin and selected user
			$id = $this->_request->getParam('id');
			
			// if no id, use user's id
			if(is_null($id)) {
				$id = $this->view->user['id'];
			
			// if id exist
			// check if connected user is the selected user
			// else check if admin
			// if not admin, limit access
			} else {
				
				if($id != $this->view->user['id']) {
					
					// if admin
					$admin = false;
					foreach($this->view->user['groups'] as $g) {
						if(strtolower($g) == 'admin') {
							$admin = true;
						}
					}
					
					if(!$admin) {
						$this->view->error = 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche';
						exit(Zend_Json::encode(array('result' => false, 'message' => 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche')));
					}
				}
			}
			
			$datas = $this->_request->getParams();
			
			// check
			$errors = array();
			
			/*
			 * REQUIRED FIELDS
			 */
			
			// firstname
			if(is_null($datas['firstname']) or empty($datas['firstname'])) {
				$errors[] = 'Prénom';
			}
			
			// lastname
			if(is_null($datas['lastname']) or empty($datas['lastname'])) {
				$errors[] = 'Nom';
			}
			
			// nickname
			if(!is_null($datas['nickname']) and !empty($datas['nickname'])) {
	
			
				$udM = new Model_UsersDatas();
					
				// check if is used
				$filter = array('keyname' => strtolower(Model_Tools::noSpecialChars(trim($datas['nickname'], ' '))));
				$exist = $udM->get($filter);
				
				// if exist and is not user's nickname
				if(isset($exist[0]) and
					strtolower(Model_Tools::noSpecialChars(trim($datas['nickname'], ' '))) != $this->view->user['keyname']) {
					$errors[] = 'Surnom (Déjà utilisé, veuillez en sélectionner un autre)';
				}
			}
			
			// birth
			if(is_null($datas['birth']) or empty($datas['birth'])) {
				$errors[] = 'Date de naissance';
			} else {
				// check format
				$test = explode('/', $datas['birth']);
				if(count($test) != 3) {
					$errors[] = 'Date de naissance';
				
				} else {
					foreach($test as $t) {
						if(!is_numeric($t)) {
							$errors[] = 'Date de naissance';
							break;
						}
					}
				}
			}
			
			// address
			if(is_null($datas['address']) or empty($datas['address'])) {
				$errors[] = 'Adresse';
			}
			
			// postcode
			if(is_null($datas['postcode']) or
				empty($datas['postcode']) or
				!is_numeric($datas['postcode']) or
				strlen($datas['postcode']) != 5) {
				$errors[] = 'Code postal';
			
			}
			
			// city
			if(is_null($datas['city']) or empty($datas['city'])) {
				$errors[] = 'Ville';
			}
			
			// telephone
			if(is_null($datas['telephone']) or empty($datas['telephone'])) {
				$errors[] = 'Téléphone';
			} else {
				$pattern = '#^0[0-9]([ .-]?[0-9]{2}){4}$#';
				if(!preg_match($pattern, $datas['telephone'])) {
					$errors[] = 'Téléphone';
				}
			}
			
			/*
			 * OTHERS FIELDS
			 */
			
			
			// facebook
			if(!is_null($datas['facebook']) and !empty($datas['facebook'])) {
				
				// check if is url
				$pattern  ='#^(http://|https://){0,1}[A-Za-z0-9][A-Za-z0-9\-\.]+[A-Za-z0-9]\.[A-Za-z]{2,}[\43-\176]*$#'; 
				if(!preg_match($pattern, $datas['facebook'])) {
					$errors[] = 'Facebook (url invalide)';
				}
			}
			
			
			// if errors
			if(!empty($errors)) {
				$message = 'Veuillez vérifier les champs suivant :';
				$message .= '<ul>';
				foreach($errors as $e) {
					$message .= '<li>'.$e.'</li>';
				}
				$message .= '</ul>';
				
				exit(Zend_Json::encode(array('result' => false, 'message' => $message)));
			}
			
			// set user's datas
			$udM = new Model_UsersDatas();
			$user = array(	'firstname' => $datas['firstname']	,
							'lastname' => $datas['lastname'],
							'keyfirstname' => strtolower(Model_Tools::noSpecialChars($datas['firstname'])),
							'nickname' => $datas['nickname'],
							'keyname' => strtolower(Model_Tools::noSpecialChars($datas['nickname'])),
							'birth' => $datas['birth'],
							'address' => $datas['address'],
							'postcode' => $datas['postcode'],
							'city' => $datas['city'],
							'telephone' => $datas['telephone'],
							'style' => $datas['style'],
							'song' => $datas['song'],
							'situation' => $datas['situation'],
							'url' => $datas['url'],
							'about' => $datas['about'],
							'facebook' => $datas['facebook'],
							'twitter' => $datas['twitter'],
							'youtube' => $datas['youtube'],
							'dailymotion' => $datas['dailymotion'],
							'update' => date('Y-m-d H:i:s', time()),
							'modifyer_id' => $this->view->user['id'],
							'modifyer_ip' => $_SERVER['REMOTE_ADDR']
						);
			$result = $udM->set($id, $user);
			
			if($result) {
			
				// Update user's view information
				$uM = new Model_User();
				$user = $uM->updateInformations($id);
				
				exit(Zend_Json::encode(array('result' => true, 'message' => 'Modifications effectuées')));
			
			} else {
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Aucune modification effectuée')));
			}
		
		}
		
		public function activateAction() {
			
			// if admin
			$admin = false;
			foreach($this->view->user['groups'] as $g) {
				if(strtolower($g) == 'admin') {
					$admin = true;
				}
			}
			
			if(!$admin) {
				$this->view->error = 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche';
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche')));
			}
			
			if($id = $this->_request->getParam('id')) {
				
				$aM = new Model_User();
				$datas = array('status' => 'active');
				$result = $aM->set($id, $datas);
				
				if($result) {
					exit(Zend_Json::encode(array('result' => true,
													'message' => 'Modifications effectuées',
													'href' => $this->view->url(array('module' => 'backend', 'controller' => 'user', 'action' => 'inactivate', 'id' => $id), null, true),
													'src' => $this->view->baseUrl().'/images/icons/active.png')));
			
				} else {
					exit(Zend_Json::encode(array('result' => false, 'message' => 'Aucune modification effectuée')));
				}
				
			} else {
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Paramètre manquant')));
			}
			
		}
		
		public function inactivateAction() {
			
			// if admin
			$admin = false;
			foreach($this->view->user['groups'] as $g) {
				if(strtolower($g) == 'admin') {
					$admin = true;
				}
			}
			
			if(!$admin) {
				$this->view->error = 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche';
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche')));
			}
			
			if($id = $this->_request->getParam('id')) {
				
				$aM = new Model_User();
				$datas = array('status' => 'inactive');
				$result = $aM->set($id, $datas);
				
				if($result) {
					exit(Zend_Json::encode(array('result' => true,
													'message' => 'Modifications effectuées',
													'href' => $this->view->url(array('module' => 'backend', 'controller' => 'user', 'action' => 'activate', 'id' => $id), null, true),
													'src' => $this->view->baseUrl().'/images/icons/inactive.png')));
			
				} else {
					exit(Zend_Json::encode(array('result' => false, 'message' => 'Aucune modification effectuée')));
				}
				
			} else {
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Paramètre manquant')));
			}
			
		}
	}
?>
